import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/normal_entity.dart';
import 'package:wanxiang_app/bean/safe_entity.dart';
import 'package:wanxiang_app/utils/constant.dart';
import '../../bean/news_entity.dart';
import '../../utils/common.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../widgets/account_textField3.dart';
import '../../widgets/myappbar.dart';
import 'package:get/get.dart';
import 'package:bot_toast/bot_toast.dart';
import 'newsDetaill.dart';

class NewsListController extends GetxController{

  @override
  void onInit() {
    super.onInit();
    Map map1 = {"id":'0',"name":'全部'};
    newsType.add(map1);

    Map map2 = {"id":'1',"name":'手游攻略'};
    newsType.add(map2);

    Map map3 = {"id":'2',"name":'端游攻略'};
    newsType.add(map3);

    Map map4 = {"id":'3',"name":'行业资讯'};
    newsType.add(map4);
    typeId = '0';
    _getSafe();
  }
  @override
  void onClose() {
    super.onClose();
  }
  List<Map> newsType = [];

  int resultData = 0;
  int index = 0;
  String typeId = '0';
  int page = 1;
  String pageCountText = '';
  List<NewsData> newsList = [];
  int totalPage = 1;
  int totalCount = 0;
  void _getSafe(){
    BotToast.showLoading();
    DioManager.getInstance().post(ServiceUrl.news, {
      'type':typeId,
      'pagesize':"20",
      'page':page.toString(),
    }, (data) async {
      BotToast.closeAllLoading();
      NewsEntity bannerEntity = NewsEntity.fromJson(jsonDecode(data));
      newsList = bannerEntity.data;

      if(newsList.isEmpty){
        totalCount = 0;
        totalPage = 1;
      }else{
        totalCount = int.parse(bannerEntity.count) ;
        totalPage = (totalCount/20).ceil() ;
      }

      pageCountText = '$page/${totalPage}';
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }
  changePage(){
    if(page > totalPage){
      page = totalPage;
    }
    _getSafe();
  }


}


class NewsListPage extends GetView<NewsListController>  {
  late NewsListController controller ;
  late BuildContext context ;
  @override
  Widget build(BuildContext context1) {

    Get.lazyPut<NewsListController>(() => NewsListController());
    controller = Get.find();
    context = context1;

    return GetBuilder<NewsListController>(
      builder: (_){
        return  Scaffold(
            appBar: MyAppBar(context: context, title: '游戏资讯',hasLeading: true,),
            backgroundColor: Colors.white,
            body:_content());
      },
    )
    ;
  }
  Widget _content(){
    return  Stack(
        children: [
          Container(
            padding: EdgeInsets.only(top: 10.h,bottom: 140.h),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                    margin: EdgeInsets.only(left: 10.w,right: 10.w),
                    child:  Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: _items(),
                    )
                )
                ,
                SizedBox(height: 1.h,),
                Expanded(child:  SingleChildScrollView(
                    child:  Column(
                      children: _newsInfoItems(),

                    )
                ))
               ,

              ],
            ),
          ),
          Positioned(child: _bottom(),bottom: 0,)
        ],
      );
  }

  Widget _tabItem(item,index){
    return InkWell(
      onTap: (){
        controller.index = index;
        controller.page = 1;
        _ediController.text = controller.page.toString();
        controller.typeId = controller.newsType[index]['id'];
        controller._getSafe();
        controller.update();
    },
      child: Container(
          margin: EdgeInsets.only(right: 20.w),
          child:  Column(
            children: [
              Text(item['name'],style: TextStyle(
              ),),
              SizedBox(height: 5.h,),
              index==controller.index?
              Container(
                height: 2.h,
                width: 60.w,
                color: Color(0xFF007BE5),
              ):Container(height: 2.h,)
            ],
          )
      )
    ) ;
  }
  List<Widget> _items(){
    List<Widget> items = [];
    for(int i=0;i<controller.newsType.length;i++){
      items.add(_tabItem(controller.newsType[i],i));
    }
    return items;
  }

  TextEditingController _ediController = TextEditingController();
  Widget _bottom(){

    return Container(
      padding: EdgeInsets.fromLTRB(10.w, 20.h, 10.w, 30.h),
      width: MediaQuery.of(context).size.width,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              controller.page==1?
              _btnDisable('首页'):_btnNormal('首页'),
              controller.page==1?
              _btnDisable('上一页'):_btnNormal('上一页'),
              _btnDisable(controller.pageCountText),
              controller.page==controller.totalPage?
              _btnDisable('下一页'):_btnNormal('下一页'),
              controller.page==controller.totalPage?
              _btnDisable('尾页'):_btnNormal('尾页'),
            ],
          ),
          SizedBox(height: 15.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text('输入页数'),
              SizedBox(width: 5.w,),
              Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5.r),
                  border: Border.all(color: const Color(0xFFEDEEEF),width: 1.w),
                ),
                width: 100.w,
                height: 30.h,
                child: AccountEdit3Text(
                    key: const ValueKey('page'),
                    keyboardType: TextInputType.number,
                    defaultText: controller.page.toString(),
                    textAlign:TextAlign.center,
                    contentStrCallBack: (String content) {
                      controller.page = int.parse(content);
                    },controllerCallBack:(TextEditingController _controller2){
                  _ediController = _controller2;
                }


                ),
              ),
              SizedBox(width: 5.w,),
              const Text('页'),
              SizedBox(width: 5.w,),
              InkWell(
                onTap: (){
                  controller._getSafe();
                },
                child: const Text('跳转'),
              )


            ],
          )
        ],
      ),
    );
  }
  Widget _btnDisable(text){
    return InkWell(
        onTap: (){

        },
        child: Container(
          alignment: Alignment.center,
          width: 60.w,
          height: 30.h,
          decoration: BoxDecoration(
            color: const Color(0xfff1f1f1),
            borderRadius: BorderRadius.circular(5.r),
            border: Border.all(color: const Color(0xFFEDEEEF),width: 1.w),
          ),
          child: Text(text,style: const TextStyle(
              color: Color(0xffc0c4cc)
          ),),
        )
    ) ;
  }

  Widget _btnNormal(text){
    return InkWell(
        onTap: (){
          if(text == '首页'){
            controller.page = 1;
            controller.changePage();
          }else  if(text == '上一页'){
            controller.page --;
            controller.changePage();
          }else  if(text == '下一页'){
            controller.page ++;
            controller.changePage();
          }else  if(text == '尾页'){
            controller.page =controller.totalPage;
            controller.changePage();
          }
          _ediController.text = controller.page.toString();
        },
        child: Container(
          alignment: Alignment.center,
          width: 60.w,
          height: 30.h,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(5.r),
            border: Border.all(color: const Color(0xFFEDEEEF),width: 1.w),
          ),
          child: Text(text,style: const TextStyle(
          ),),
        )
    ) ;
  }


  List<Widget> _newsInfoItems(){
    List<Widget> items = [];

    for(int i = 0;i<controller.newsList.length;i++){
      items.add(_newsInfoItem(controller.newsList[i]));
    }

    return items;
  }
  Widget _newsInfoItem(NewsData item){
    return InkWell(
        onTap: (){
          Get.to(()=>NewsDetailPage(),arguments: {
            "id":item.id.toString(),
          },preventDuplicates:false);
        },
        child:  Container(
          margin: EdgeInsets.only(left: 10.w,right: 5.w,top: 10.h),
          child: Row(
            children: [
              Container(
                  width: 120.w,
                  height: 100.w,
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(12.r),
                    child:Stack(
                      children: [
                        Image.network(item.imgUrl,fit:BoxFit.cover,
                          width: 120.w,
                          height: 103.w,

                        ),
                      ],
                    ),
                  )
              ),
              SizedBox(width: 14.w,),
              Container(
                  width: MediaQuery.of(context).size.width - 29.w - 14.w - 100.w - 20.w,
                  height: 103.w,
                  child:  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(item.title,
                        style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,fontWeight: FontWeight.bold),maxLines: 2,    textAlign: TextAlign.left,
                        overflow: TextOverflow.ellipsis,),
                      SizedBox(height: 2.h,),

                      Text(item.introduce,
                        style: TextStyle(color: Color(0xFF666666),fontSize: 13.sp),maxLines: 2,    textAlign: TextAlign.left,
                        overflow: TextOverflow.ellipsis,),

                      SizedBox(height: 6.h,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(Common.transferDate(item.updateTime) ,
                              style: TextStyle(color: Color(0xFF999999),fontSize: 13.sp)),
                          Row(
                            children: [
                              Image.asset(Constant.IMG_BASE+'eye_open.png',width: 16.w,height: 10.h,),
                              SizedBox(width: 5.w,),
                              Text(item.lookNum.toString(),
                                  style: TextStyle(color: Color(0xFF999999),fontSize: 13.sp)),
                            ],
                          )
                        ],
                      )
                    ],
                  )
              )

            ],
          ),
        )
    );
  }
}